package com.xuxingcan.findmyvoice.Activity;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.avos.avoscloud.AVUser;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.rey.material.app.DialogFragment;
import com.rey.material.widget.EditText;
import com.xuxingcan.findmyvoice.Fragment.SquareFragment;
import com.xuxingcan.findmyvoice.R;
import com.xuxingcan.findmyvoice.Util.BitmapUtil;
import com.xuxingcan.findmyvoice.Util.LeanCloudUtil;
import com.xuxingcan.findmyvoice.Util.UpdateUtil;


/**
 * Created by Administrator on 2016/3/28.
 */
public class MainActivity extends BaseActivity {
    private DrawerLayout mDrawerLayout;
    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.test)          // 设置图片下载期间显示的图片
            .showImageForEmptyUri(R.drawable.test)  // 设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.drawable.test)       // 设置图片加载或解码过程中发生错误显示的图片
            .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
            .build();                                   // 创建配置过得DisplayImageOption对象
    private ImageView userIcon;
    private TextView userName;
    private static final int LOGIN_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.root);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.fragment, new SquareFragment(this));
        transaction.commit();
        userIcon = (ImageView) findViewById(R.id.userIcon);
        userName = (TextView) findViewById(R.id.user_name);
        findViewById(R.id.add_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (AVUser.getCurrentUser() == null) {
                            showLongToast("请先登录!");
                            startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN_CODE);
                        } else {
                            startActivity(new Intent(MainActivity.this, NewItemActivity.class));
                        }
                    }
                }, 300);
            }
        });
        findViewById(R.id.item_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AVUser.getCurrentUser() == null) {
                    showLongToast("请先登录!");
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN_CODE);
                } else {
                    startActivity(new Intent(MainActivity.this, NewItemActivity.class));
                }
            }
        });
        findViewById(R.id.item_change_password).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AVUser.getCurrentUser() == null) {
                    showLongToast("请先登录!");
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN_CODE);
                } else {
                    showDialog("修改密码", R.layout.change_password_dialog, "确定", "取消", new DialogCallback() {
                        @Override
                        public boolean onPositiveActionClicked(DialogFragment fragment) {
                            EditText originPasswordEditText = (EditText) fragment.getDialog().findViewById(R.id.origin_password);
                            EditText newPasswordEditText = (EditText) fragment.getDialog().findViewById(R.id.new_password);
                            EditText repeateNewPasswordEditText = (EditText) fragment.getDialog().findViewById(R.id.repeate_new_password);
                            String originPassword = originPasswordEditText.getText().toString().trim();
                            String newPassword = newPasswordEditText.getText().toString().trim();
                            String repeateNewPassword = repeateNewPasswordEditText.getText().toString().trim();
                            if (originPassword == null || originPassword.length() == 0 || newPassword == null
                                    || newPassword.length() == 0 || repeateNewPassword == null || repeateNewPassword.length() == 0) {
                                showDialog("发生了一点错误", "密码不能为空", "我知道了");
                                return true;
                            }
                            if (originPassword.length() < 8 || newPassword.length() < 8 || repeateNewPassword.length() < 8) {
                                showDialog("发生了一点错误", "密码长度不足8位", "我知道了");
                                return true;
                            }
                            if (!newPassword.equals(repeateNewPassword)) {
                                showDialog("发生了一点错误", "两次输入的密码不相同", "我知道了");
                                return true;
                            }
                            LeanCloudUtil.updatePassword(originPassword, newPassword, new LeanCloudUtil.updatePasswordCallback() {
                                @Override
                                public void onSuccess() {
                                    showLongToast("密码修改成功");
                                }

                                @Override
                                public void onFail(Exception e) {
                                    showLongToast("密码修改失败\n" + e.getMessage());
                                }
                            });
                            return false;
                        }

                        @Override
                        public boolean onNegativeActionClicked(DialogFragment fragment) {
                            return false;
                        }
                    });
                }
            }
        });
        findViewById(R.id.item_login_out).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog("退出", "确定要退出吗？", "确定", "取消", new DialogCallback() {
                    @Override
                    public boolean onPositiveActionClicked(DialogFragment fragment) {
                        if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
                            mDrawerLayout.closeDrawers();
                        }
                        AVUser.logOut();
                        initUser();
                        return false;
                    }

                    @Override
                    public boolean onNegativeActionClicked(DialogFragment fragment) {
                        return false;
                    }
                });
            }
        });
        findViewById(R.id.item_feed_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, FeedbackActivity.class));
            }
        });
        userIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AVUser.getCurrentUser() == null) {
                    startActivityForResult(new Intent(MainActivity.this, LoginActivity.class), LOGIN_CODE);
                }
            }
        });
//        LeanCloudUtil.getFilePathName(Environment.getExternalStorageDirectory());
        UpdateUtil.checkUpdateInBackgroundThread(this);
        initUser();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOGIN_CODE) {
            initUser();
        }
    }

    private void initUser() {
        AVUser mAvUser = AVUser.getCurrentUser();
        if (mAvUser == null) {
            Bitmap m = BitmapUtil.getRoundBitmap(BitmapUtil.corpBitmapWithGivenParameter(BitmapFactory.decodeResource(getResources(), R.drawable.user_icon), 500, 500));
            userIcon.setImageBitmap(m);
            userName.setText("请登录");
            findViewById(R.id.item_login_out).setVisibility(View.GONE);
        } else {
            findViewById(R.id.item_login_out).setVisibility(View.VISIBLE);
            ImageLoader.getInstance().loadImage(mAvUser.getAVFile(LeanCloudUtil.KEY_USER_ICON).getUrl(), new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {

                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    userIcon.setImageBitmap(BitmapUtil.getRoundBitmap(BitmapUtil.corpBitmapWithGivenParameter(loadedImage, 500, 500)));
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {

                }
            });
            userName.setText(AVUser.getCurrentUser().getUsername());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
            mDrawerLayout.closeDrawers();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
